<template>
  <div class="statistics-container" v-loading="loading">
    <h2>重症医学科收治患者前10位病种</h2>
    <div class="filter-container">
      <div class="date-picker-group">
        <span class="label">时间范围：</span>
        <el-date-picker
          v-model="dateRange"
          type="monthrange"
          range-separator="至"
          start-placeholder="开始月份"
          end-placeholder="结束月份"
          format="YYYY-MM"
          value-format="YYYY-MM"
          @change="handleDateChange"
        />
      </div>
      <el-button type="primary" @click="getData">查询</el-button>
      <el-button type="success" @click="exportToExcel" :disabled="dataList.length === 0">导出Excel</el-button>
    </div>
    <!-- <div class="chart-container" ref="chartRef"></div> -->
    <el-table :data="dataList" :header-cell-style="{ background: '#409EFF', color: '#fff' }">
      <el-table-column label="病种名称" prop="title" align="center"></el-table-column>
      <el-table-column label="数量" prop="TOTAL" align="center"></el-table-column>
      <template #empty>
        <el-empty description="暂无数据"></el-empty>
      </template>
    </el-table>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount, watch } from 'vue';
import * as echarts from 'echarts';
import { getQuery } from "../api/book";
import { utils, writeFile } from 'xlsx';

// 定义响应式引用
const chartRef = ref(null);
let myChart = null;
const dataList = ref([]);
const loading = ref(false);
const dateRange = ref([]);

// 设置默认时间范围
const initDefaultDates = () => {
  const now = new Date();
  const year = now.getFullYear();
  const startMonth = `${year}-01`;
  const endMonth = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}`;
  dateRange.value = [startMonth, endMonth];
};

// 初始化默认日期
// initDefaultDates();

// 获取月份的最后一天
const getLastDayOfMonth = (year, month) => {
  // month是0-11的值，所以需要减1
  return new Date(year, month, 0).getDate();
};

// 根据年月获取该月的最后一天日期字符串
const getEndOfMonth = (yearMonth) => {
  if (!yearMonth) return "";
  const [year, month] = yearMonth.split("-");
  const lastDay = getLastDayOfMonth(parseInt(year), parseInt(month));
  return `${yearMonth}-${lastDay}`;
};

const options = {
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      type: 'shadow'
    },
    formatter: '{b}: {c}例'
  },
  grid: {
    left: '10%',
    right: '10%',
    bottom: '25%',
    containLabel: true
  },
  xAxis: {
    type: 'category',
    axisLabel: {
      interval: 0,
      formatter: '{value}',
      fontSize: 12,
    }
  },
  yAxis: {
    type: 'value',
    axisLabel: {
      formatter: '{value}'
    },
    splitLine: {
      show: true,
      lineStyle: {
        color: '#eee'
      }
    }
  },
  series: [{
    name: '病例数',
    type: 'bar',
    label: {
      show: true,
      position: 'top',
      formatter: '{c}',
      fontSize: 12,
      color: '#333'
    },
    itemStyle: {
      color: '#3498db'
    },
    emphasis: {
      itemStyle: {
        color: '#2980b9'
      }
    }
  }]
};

// 窗口大小调整处理
const handleResize = () => {
  if (myChart) {
    myChart.resize();
  }
};

// 渲染图表
const renderChart = () => {
  if (!myChart && chartRef.value) {
    myChart = echarts.init(chartRef.value);
    window.addEventListener('resize', handleResize);
  }

  if (myChart) {
    // 计算Y轴最大值
    const maxValue = Math.max(...dataList.value.map(item => item.TOTAL), 10);
    const yAxisMax = Math.ceil(maxValue / 10) * 10 + 10; // 增加一些空间以容纳标签

    // 更新配置项的数据
    const updatedOptions = {
      ...options,
      yAxis: {
        ...options.yAxis,
        max: yAxisMax
      },
      xAxis: {
        ...options.xAxis,
        data: dataList.value.map(item => item.title)
      },
      series: [{
        ...options.series[0],
        data: dataList.value.map(item => item.TOTAL)
      }]
    };

    myChart.setOption(updatedOptions, true);
  }
};

// 获取数据
const getData = () => {
  const startMonth = dateRange.value && dateRange.value[0] ? dateRange.value[0] : '';
  const endMonth = dateRange.value && dateRange.value[1] ? dateRange.value[1] : '';

  // 获取每个月的正确最后一天
  const startDate = startMonth ? `${startMonth}-01 00:00:00` : "";
  const endDate = endMonth ? `${getEndOfMonth(endMonth)} 23:59:59` : "";

  const data = {
    typeName: "seekGroupCount",
    params: {
      "1": startDate,
      "2": endDate
    }
  };
  
  loading.value = true;
  getQuery(data).then(res => {
    dataList.value = res;
    loading.value = false;
  }).catch(err => {
    console.error('获取数据失败:', err);
    loading.value = false;
  });
};

// 导出Excel
const exportToExcel = () => {
  if (!dataList.value || dataList.value.length === 0) {
    return;
  }

  // 准备导出数据
  const exportData = dataList.value.map(item => ({
    '病种名称': item.title,
    '数量': item.TOTAL
  }));

  // 创建工作表
  const ws = utils.aoa_to_sheet([
    ['病种名称', '数量']
  ]);
  
  // 添加数据
  utils.sheet_add_json(ws, exportData, { origin: 'A2' });
  
  // 合并标题单元格
  const title = `重症医学科收治患者前10位病种(${dateRange.value[0]}至${dateRange.value[1]})`;
  ws['A1'] = { t: 's', v: title };
  ws['!merges'] = [{ s: { r: 0, c: 0 }, e: { r: 0, c: 1 } }]; // 合并A1:B1
  
  // 设置列宽
  ws['!cols'] = [
    { wch: 20 }, // 病种名称列宽
    { wch: 10 }  // 数量列宽
  ];
  
  // 创建工作簿
  const wb = utils.book_new();
  utils.book_append_sheet(wb, ws, '病种统计');
  
  // 导出文件
  const filename = `${title}.xlsx`;
  writeFile(wb, filename);
};

// 日期变更处理
const handleDateChange = () => {
  // 可以在这里添加日期校验逻辑
  if (dateRange.value && dateRange.value[0] && dateRange.value[1]) {
    if (new Date(dateRange.value[0]) > new Date(dateRange.value[1])) {
      // 如果开始时间晚于结束时间，可以提示或自动调整
      console.warn('开始月份不能晚于结束月份');
    }
  }
};

// 监听数据变化，数据变化后渲染图表
watch(dataList, (newData) => {
  if (newData && newData.length > 0) {
    renderChart();
  }
});

onMounted(() => {
  // getData();
});

// 组件卸载前清理资源
onBeforeUnmount(() => {
  if (myChart) {
    myChart.dispose();
  }
  window.removeEventListener('resize', handleResize);
});
</script>

<style scoped>
.statistics-container {
  width: 92vw;
  padding: 20px;
}

.filter-container {
  display: flex;
  align-items: center;
  gap: 20px;
  margin-bottom: 20px;
  flex-wrap: wrap;
}

.date-picker-group {
  display: flex;
  align-items: center;
}

.label {
  margin-right: 10px;
  white-space: nowrap;
}

.chart-container {
  width: 1000px;
  height: 400px;
  margin: 20px auto;
}

@media (max-width: 768px) {
  .filter-container {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .date-picker-group {
    width: 100%;
    margin-bottom: 10px;
  }
  
  .label {
    margin-right: 5px;
  }
  
  .chart-container {
    width: 100%;
    height: 300px;
  }
}
</style>